package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.MultiAutoCompleteTextView;
import android.widget.ProgressBar;
import android.widget.Toast;

/** Activity for searching stories and users with autocomplete mechanism.
 *
 */
public class SearchActivity extends Activity {

	private Activity currentActivity;

	private AutoCompleteTextView locationView;
	private MultiAutoCompleteTextView keywordView;
	private DatePicker dateView;
	private Button searchButton;
	private ProgressBar progressBar;

	private String location;
	private String keywords;
	private String date;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		final ActionBar bar = getActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		bar.setDisplayShowTitleEnabled(false);

		currentActivity = this;

		locationView = (AutoCompleteTextView) findViewById(R.id.search_location_input);
		keywordView = (MultiAutoCompleteTextView) findViewById(R.id.search_keywords_input);
		dateView = (DatePicker) findViewById(R.id.datePicker1);
		searchButton = (Button) findViewById(R.id.search_button);
		progressBar = (ProgressBar) findViewById(R.id.progressBar_searchbutton);
		progressBar.setVisibility(View.GONE);

		ArrayAdapter<String> locationAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Utils.locations);

		locationView.setAdapter(locationAdapter);

		ArrayAdapter<String> keywordAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Utils.keywords);

		keywordView.setAdapter(keywordAdapter);
		keywordView
				.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				progressBar.setVisibility(View.VISIBLE);
				SearchTask sTask = new SearchTask();
				sTask.execute((Void) null);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.home_button:
			Intent mainIntent = new Intent(this, MainActivity.class);
			startActivity(mainIntent);
			return true;
		case R.id.recommendations_button:
			Intent recomIntent = new Intent(this, RecommendationsActivity.class);
			startActivity(recomIntent);
			return true;
		case R.id.profile_button:
			Intent profileIntent = new Intent(this, ProfileActivity.class);
			startActivity(profileIntent);
			return true;
		case R.id.search_button:
			return true;
		case R.id.following_button:
			Intent followIntent = new Intent(this, FollowingActivity.class);
			startActivity(followIntent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Represents an asynchronous Search task for requesting search using
	 * parameters provided by the user. Then directs the user to search results
	 * page.
	 * 
	 */
	@SuppressLint("SimpleDateFormat")
	public class SearchTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			// progressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected String doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "Search");
			keywords = keywordView.getText().toString();
			location = locationView.getText().toString();
			date = dateView.getYear() + "-" + (dateView.getMonth() + 1) + "-"
					+ dateView.getDayOfMonth();
			Date dateNow = new Date();
			Date dateGiven = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String nowStr = sdf.format(dateNow);
			try {
				dateGiven = new SimpleDateFormat("yyyy-MM-dd").parse(date);
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (dateGiven.after(dateNow)) {
				this.cancel(false);
			} else if (date.equals(nowStr)) {
				date = null;
			}
			String jsonResponse = null;
			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs
						.add(new BasicNameValuePair("keywords", keywords));
				nameValuePairs
						.add(new BasicNameValuePair("location", location));
				nameValuePairs.add(new BasicNameValuePair("date", date));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				jsonResponse = EntityUtils.toString(response.getEntity());

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return jsonResponse;
		}

		@Override
		protected void onPostExecute(final String result) {

			progressBar.setVisibility(View.GONE);
			Intent resultIntent = new Intent(currentActivity,
					SearchResults.class);
			resultIntent.putExtra("result", result);
			startActivity(resultIntent);
		}

		@Override
		protected void onCancelled() {
			progressBar.setVisibility(View.GONE);
			Toast.makeText(getApplicationContext(),
					"Please enter a valid date!", Toast.LENGTH_SHORT).show();
		}
	}

}
